package com.axun.fileexplore

import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.support.v4.app.FragmentActivity
import android.support.v4.content.ContextCompat
import com.tbruyelle.rxpermissions2.RxPermissions

/**
 * Created by hz-java on 2018/8/18.
 */

object PermissionRequest {


    var permissions = arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)

    fun requestAll(context: Context, callback: OnPermissionCallback) {

        request(context, permissions, callback)

    }

    private fun request(context: Context, permissions: Array<String>, callback: OnPermissionCallback) {
        RxPermissions(context as FragmentActivity).request(*permissions)
                .subscribe { aBoolean ->
                    if (aBoolean!!) {
                        callback.onPermissionSuccess()
                    } else {
                        callback.onPermissionFailed()
                    }
                }
    }


    /**
     * 判断权限集合
     * permissions 权限数组
     * return true-表示没有改权限  false-表示权限已开启
     */
    fun lacksPermissions(mContexts: Context, permissions: Array<String>): Boolean {
        for (permission in permissions) {
            if (lacksPermission(mContexts, permission)) {
                return true
            }
        }
        return false
    }

    /**
     * 判断是否缺少权限
     */
    private fun lacksPermission(mContexts: Context, permission: String): Boolean {
        return ContextCompat.checkSelfPermission(mContexts, permission) == PackageManager.PERMISSION_DENIED
    }

    interface OnPermissionCallback {
        fun onPermissionSuccess()
        fun onPermissionFailed()
    }
}
